package com.itheima.interceptor;

import com.itheima.utnil.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

//自定义拦截器
@Component
public class TokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求路径
        String url = request.getRequestURL().toString();
//        1/2、判断路径是否需要拦截
        if (url.contains("/login")) {
            return true;
        }
//        1/3、获取请求头令牌
        String token = request.getHeader("token");


        if (ObjectUtils.isEmpty(token) || JwtUtils.parseJwt(token) == null) {

//            1/4、校验通过，放行请求
            response.setStatus(401);
            return false;
        }

        return true;


    }


}
